package com.connect;

import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import sun.misc.BASE64Decoder;
public class DiscuzPassport {
	 public static String encrypt(String src, String key) {
	  Random random = new Random();
	  random.setSeed(System.currentTimeMillis());
	  String rand = "" + random.nextInt() % 32000;
	  String encKey = Encryption.generateKey(rand, "MD5");
	  int ctr = 0;
	  String tmp = "";
	  for (int i = 0; i < src.length(); i++) {
	   ctr = (ctr == encKey.length() ? 0 : ctr);
	   tmp += encKey.charAt(ctr);
	   char c = (char) (src.charAt(i) ^ encKey.charAt(ctr));
	   tmp += c;
	   ctr++;
	  }
	  String passportKey = passportKey(tmp, key);
	  return new sun.misc.BASE64Encoder().encode(passportKey.getBytes());
	 }
	 
	 public static String decrypt(String src, String key) {
	  byte[] bytes = null;
	  try {
	   bytes = new BASE64Decoder().decodeBuffer(src);
	   src = new String(bytes);
	  } catch (Exception e) {
	   return null;
	  }
	  src = passportKey(src, key);
	  String tmp = "";
	  for (int i = 0; i < src.length(); ++i) {
	   char c = (char) (src.charAt(i) ^ src.charAt(++i));
	   tmp += c;
	  }
	  return tmp;
	 }
	 
	 public static String passportKey(String src, String key) {
	  String encKey = Encryption.generateKey(key, "MD5");
	  int ctr = 0;
	  String tmp = "";
	  for (int i = 0; i < src.length(); ++i) {
	   ctr = (ctr == encKey.length() ? 0 : ctr);
	   char c = (char) (src.charAt(i) ^ encKey.charAt(ctr));
	   tmp += c;
	   ctr++;
	  }
	  return tmp;
	 }
	 
	 public static String passportEncode(Map data) {
	  Set keys = data.keySet();
	  String key = "";
	  String ret = "";
	  Iterator iterator = keys.iterator();
	  while (iterator.hasNext()) {
	   key = (String) iterator.next();
	   try
	   {
	    ret += key + "=" + (String) data.get(key) + "&";
	   }
	   catch (Exception e)
	   {
	    return "";
	   }
	  }
	  if (ret.length() > 0)
	   return ret.substring(0, ret.length() - 1);
	  return "";
	 }
}
